package com.ara.common.kernel.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by XieXin on 2017-09-05.
 * 基础Fragment
 */

public abstract class BaseFragment<VB extends ViewBinding> extends Fragment implements View.OnClickListener {
    protected VB binding;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = getViewBinding(inflater, container);
        initView(binding.getRoot());
        initView(binding.getRoot(), savedInstanceState);
        initListener();
        initData();
        return binding.getRoot();
    }

    private VB getViewBinding(LayoutInflater inflater, @Nullable ViewGroup container) {
        try {
            //获取当前类的Type
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {//判断是否支持泛型
                //获取泛型中的实例
                Class<VB> clazz = (Class<VB>) ((ParameterizedType) type).getActualTypeArguments()[0];
                //反射VB里面的inflate方法
                Method method = clazz.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
                //调用方法获得VB
                return (VB) method.invoke(null, inflater, container, false);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    protected abstract void initView(@Nullable View view);

    public void initData() {
    }

    public void initListener() {
    }

    @Override
    public void onClick(View view) {
    }

    protected void initView(@Nullable View view, @Nullable Bundle savedInstanceState) {
    }
}
